<template>
  <div class="chat-history-manager-page">
    <div class="page-header">
      <h1>对话管理</h1>
      <p>管理系统中的所有对话历史记录，包括查看、搜索和分析对话数据</p>
    </div>

    <!-- 统计信息 -->
    <div class="stats-section">
      <a-row :gutter="16">
        <a-col :span="6">
          <a-card size="small">
            <a-statistic title="对话总数" :value="chatHistoryList.totalRow" />
          </a-card>
        </a-col>
        <a-col :span="6">
          <a-card size="small">
            <a-statistic title="当前页数量" :value="chatHistoryList.records?.length || 0" />
          </a-card>
        </a-col>
        <a-col :span="6">
          <a-card size="small">
            <a-statistic title="用户消息" :value="userMessageCount" />
          </a-card>
        </a-col>
        <a-col :span="6">
          <a-card size="small">
            <a-statistic title="AI消息" :value="aiMessageCount" />
          </a-card>
        </a-col>
      </a-row>
    </div>

    <!-- 搜索区域 -->
    <div class="search-section">
      <a-card>
        <a-form layout="inline" :model="searchForm">
          <a-form-item label="消息内容">
            <a-input
              v-model:value="searchForm.message"
              placeholder="请输入消息内容关键词"
              style="width: 200px"
              allow-clear
            />
          </a-form-item>
          <a-form-item label="消息类型">
            <a-select
              v-model:value="searchForm.messageType"
              placeholder="请选择消息类型"
              style="width: 120px"
              allow-clear
            >
              <a-select-option value="user">用户消息</a-select-option>
              <a-select-option value="ai">AI消息</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="应用ID">
            <a-input
              v-model:value="searchForm.appId"
              placeholder="请输入应用ID"
              style="width: 120px"
              allow-clear
            />
          </a-form-item>
          <a-form-item label="用户ID">
            <a-input
              v-model:value="searchForm.userId"
              placeholder="请输入用户ID"
              style="width: 120px"
              allow-clear
            />
          </a-form-item>
          <a-form-item>
            <a-space>
              <a-button type="primary" @click="handleSearch" :loading="loading">
                <SearchOutlined />
                搜索
              </a-button>
              <a-button @click="handleReset">
                <ReloadOutlined />
                重置
              </a-button>
            </a-space>
          </a-form-item>
        </a-form>
      </a-card>
    </div>

    <!-- 对话历史列表 -->
    <div class="table-section">
      <a-table
        :columns="columns"
        :data-source="chatHistoryList.records"
        :loading="loading"
        :pagination="false"
        row-key="id"
        size="middle"
        :scroll="{ x: 1200 }"
      >
        <!-- 消息内容 -->
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'message'">
            <div class="message-content">
              <a-tooltip :title="record.message" placement="topLeft">
                <div class="message-text">{{ record.message }}</div>
              </a-tooltip>
            </div>
          </template>

          <!-- 消息类型 -->
          <template v-else-if="column.key === 'messageType'">
            <a-tag :color="record.messageType === 'user' ? 'blue' : 'green'">
              {{ record.messageType === 'user' ? '用户消息' : 'AI消息' }}
            </a-tag>
          </template>

          <!-- 应用信息 -->
          <template v-else-if="column.key === 'appId'">
            <div class="app-info">
              <div class="app-id">ID: {{ record.appId }}</div>
              <div v-if="record.app" class="app-name">{{ record.app.appName }}</div>
            </div>
          </template>

          <!-- 用户信息 -->
          <template v-else-if="column.key === 'userId'">
            <div class="user-info">
              <div class="user-id">ID: {{ record.userId }}</div>
              <div v-if="record.user" class="user-name">{{ record.user.userName }}</div>
            </div>
          </template>

          <!-- 创建时间 -->
          <template v-else-if="column.key === 'createTime'">
            <div class="time-info">
              <div class="date">{{ formatDate(record.createTime) }}</div>
              <div class="time">{{ formatTime(record.createTime) }}</div>
            </div>
          </template>

          <!-- 操作 -->
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button type="link" size="small" @click="handleViewApp(record)">
                <EyeOutlined />
                查看应用
              </a-button>
              <a-button type="link" size="small" @click="handleViewChat(record)">
                <MessageOutlined />
                查看对话
              </a-button>
            </a-space>
          </template>
        </template>
      </a-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <a-pagination
          v-model:current="searchForm.pageNum"
          v-model:page-size="searchForm.pageSize"
          :total="chatHistoryList.totalRow"
          :show-size-changer="true"
          :show-quick-jumper="true"
          :show-total="(total: number, range: [number, number]) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`"
          @change="handlePageChange"
          @show-size-change="handlePageChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { SearchOutlined, ReloadOutlined, EyeOutlined, MessageOutlined } from '@ant-design/icons-vue'
import { listAllChatHistoryByPageForAdmin } from '@/api/chatHistoryController'

const router = useRouter()

// 表格列定义
const columns = [
  {
    title: '消息内容',
    key: 'message',
    width: 300,
    ellipsis: true
  },
  {
    title: '消息类型',
    key: 'messageType',
    width: 100
  },
  {
    title: '应用信息',
    key: 'appId',
    width: 150
  },
  {
    title: '用户信息',
    key: 'userId',
    width: 150
  },
  {
    title: '创建时间',
    key: 'createTime',
    width: 180
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right'
  }
]

// 搜索表单
const searchForm = reactive({
  pageNum: 1,
  pageSize: 20,
  message: '',
  messageType: undefined as string | undefined,
  appId: undefined as string | undefined,
  userId: undefined as string | undefined
})

// 对话历史列表数据
const chatHistoryList = reactive<API.PageChatHistory>({
  records: [],
  totalRow: 0,
  pageNumber: 1,
  pageSize: 20,
  totalPage: 0,
  optimizeCountQuery: true
})

// 加载状态
const loading = ref(false)

// 统计数据
const userMessageCount = computed(() => {
  return chatHistoryList.records?.filter(record => record.messageType === 'user').length || 0
})

const aiMessageCount = computed(() => {
  return chatHistoryList.records?.filter(record => record.messageType === 'ai').length || 0
})

// 加载对话历史列表
const loadChatHistoryList = async () => {
  loading.value = true
  try {
    const response = await listAllChatHistoryByPageForAdmin(searchForm)
    if (response.data.code === 200 && response.data.data) {
      Object.assign(chatHistoryList, response.data.data)
    }
  } catch (error) {
    message.error('加载对话历史列表失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  searchForm.pageNum = 1
  loadChatHistoryList()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    pageNum: 1,
    pageSize: 20,
    message: '',
    messageType: undefined,
    appId: undefined,
    userId: undefined
  })
  loadChatHistoryList()
}

// 分页变化
const handlePageChange = (page: number, pageSize: number) => {
  searchForm.pageNum = page
  searchForm.pageSize = pageSize
  loadChatHistoryList()
}

// 查看应用
const handleViewApp = (record: API.ChatHistory) => {
  if (record.appId) {
    router.push(`/app/detail/${record.appId}`)
  }
}

// 查看对话
const handleViewChat = (record: API.ChatHistory) => {
  if (record.appId) {
    router.push(`/app/chat/${record.appId}`)
  }
}

// 格式化日期
const formatDate = (dateStr?: string) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  })
}

// 格式化时间
const formatTime = (dateStr?: string) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 页面加载时获取数据
onMounted(() => {
  loadChatHistoryList()
})
</script>

<style scoped>
.chat-history-manager-page {
  padding: 24px;
  background: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #1a1a1a;
}

.page-header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.stats-section {
  margin-bottom: 24px;
}

.search-section {
  margin-bottom: 24px;
}

.table-section {
  background: white;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.message-content {
  max-width: 280px;
}

.message-text {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  line-height: 1.5;
}

.app-info,
.user-info {
  line-height: 1.4;
}

.app-id,
.user-id {
  font-size: 12px;
  color: #666;
}

.app-name,
.user-name {
  font-size: 13px;
  color: #1a1a1a;
  font-weight: 500;
}

.time-info {
  line-height: 1.4;
}

.date {
  font-size: 13px;
  color: #1a1a1a;
}

.time {
  font-size: 12px;
  color: #666;
}

.pagination-wrapper {
  margin-top: 24px;
  text-align: right;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chat-history-manager-page {
    padding: 16px;
  }

  .stats-section .ant-col {
    margin-bottom: 16px;
  }

  .search-section .ant-form-item {
    margin-bottom: 16px;
  }
}
</style>
